package com.resou.reader.bookstore.category.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.resou.reader.R;
import com.resou.reader.api.entry.SortSubBean;
import com.resou.reader.bookshelf.listener.OnItemClickListener;

import java.util.List;

/**
 * Created by ${Garrett} on 2018/9/29.
 * Contact me krouky@outlook.com
 */
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {

    private final OnItemClickListener listener;
    private List<SortSubBean> list;

    public CategoryAdapter(OnItemClickListener listener) {
        this.listener = listener;
    }

    public void setData(List<SortSubBean> data) {
        this.list = data;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new ViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_all_category, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
        SortSubBean bean = list.get(i);
        if (bean == null) {
            return;
        }
        viewHolder.categoryName.setText(bean.getCategoryName());
        Glide.with(viewHolder.categoryName.getContext()).load(bean.getCoverUrl() == null ? "" : bean.getCoverUrl()).into(viewHolder.ivImg);
        viewHolder.tvBookNum.setText(bean.getNovelCount() + "本");
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        TextView categoryName;
        ImageView ivImg;
        TextView tvBookNum;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            categoryName = itemView.findViewById(R.id.category_name);
            ivImg = itemView.findViewById(R.id.ivImg);
            ivImg = itemView.findViewById(R.id.ivImg);
            tvBookNum = itemView.findViewById(R.id.tvBookNum);
            categoryName.getPaint().setFakeBoldText(true);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.onItemClicked(CategoryAdapter.this, v, getAdapterPosition());
                    }
                }
            });
        }
    }
}
